package com.wondertek.poms.service.controller;

import com.alibaba.excel.EasyExcel;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.exception.MessageCodes;
import com.wondertek.poms.common.log.MethodLog;
import com.wondertek.poms.common.utils.CopyUtils;
import com.wondertek.poms.common.utils.validate.ValidateFilter;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.service.IClassifyService;
import com.wondertek.poms.core.service.IPcPrdInfoRuleService;
import com.wondertek.poms.core.service.IPrdRuleSecondClassifyService;
import com.wondertek.poms.dao.po.PrdInfoRule;
import com.wondertek.poms.dao.po.PrdRuleSecondClassify;
import com.wondertek.poms.service.listener.UploadDataListener;
import com.wondertek.poms.service.util.BeanPropertiesUtil;
import com.wondertek.poms.service.vo.PrdInfoRuleImportVo;
import com.wondertek.poms.service.vo.PrdInfoRuleVo;
import com.wondertek.poms.service.vo.PrdRuleSecondClassifyVo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author evan0213
 * @description
 */
@Slf4j
@RestController
@RequestMapping("prd-info-rule")
public class PrdInfoRuleController {
	@Autowired
	private IPcPrdInfoRuleService prdInfoRuleService;
	@Autowired
	private BeanPropertiesUtil beanPropertiesUtil;
	@Autowired
	private IPrdRuleSecondClassifyService prdRuleSecondClassifyService;
	@Autowired
	private IClassifyService classifyService;

	@ApiOperation(value = "商品包规则 列表", notes = "商品包规则 列表")
	@GetMapping("/list")
	@MethodLog(module = "商品包规则列表")
	public ResultBean list(Long prdInfoId, Integer type) {
		if (prdInfoId == null || type == null) {
			return ResultBean.error("商品包id和规则类型都不能为空");
		}
		List<PrdInfoRule> list = prdInfoRuleService.findAllByPrdInfoIdAndIsprdSel(prdInfoId, type);
		if (list.size() > 0) {
			for (PrdInfoRule prdInfoRule : list) {
				Set<PrdRuleSecondClassify> secondClassifySet = prdRuleSecondClassifyService.findAllByPrdRuleId(prdInfoRule.getPrdRuleId());
				prdInfoRule.setSecondClassifys(secondClassifySet);
			}
		}
		return ResultBean.ok(list);
	}

	@ApiOperation(value = "商品包规则 新增", notes = "商品包规则 新增")
	@PostMapping("/add")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "firstClassify", required = false, value = "一级分类"),
			@ApiImplicitParam(name = "assist", required = false, value = "辅助分类"),
			@ApiImplicitParam(name = "output", required = false, value = "是否可输出"),
			@ApiImplicitParam(name = "hasVideo", required = false, value = "是否包含媒体文件"),
			@ApiImplicitParam(name = "contentLevel", required = false, value = "内容评级"),
			@ApiImplicitParam(name = "formType", required = false, value = "剧集类型"),
			@ApiImplicitParam(name = "recommendation", required = false, value = "推荐标签"),
			@ApiImplicitParam(name = "category", required = false, value = "内容类别"),
			@ApiImplicitParam(name = "freeType", required = false, value = "资费类型"),
			@ApiImplicitParam(name = "mediaUsageCode", required = false, value = "码率"),
			@ApiImplicitParam(name = "optimal", required = false, value = "是否最优"),
			@ApiImplicitParam(name = "copyrightType", required = false, value = "版权类型"),
			@ApiImplicitParam(name = "copyRightCpId", required = false, value = "版权所属CP"),
			@ApiImplicitParam(name = "copytypeTal", required = false, value = "版权终端"),
			@ApiImplicitParam(name = "copyRightScope", required = false, value = "版权授权范围"),
			@ApiImplicitParam(name = "needDRM", required = false, value = "数字版权保护"),
			@ApiImplicitParam(name = "authorizationWay", required = false, value = "授权方式"),
			@ApiImplicitParam(name = "copyRightArea", required = false, value = "数字版权保护"),
			@ApiImplicitParam(name = "isprdSel", required = true, value = "规则类型"),
			@ApiImplicitParam(name = "targetPrdInfo", required = false, value = "目标产品包"),
			@ApiImplicitParam(name = "secondClassifys", required = false, value = "二级分类"),
			@ApiImplicitParam(name = "targetPrdInfo", required = false, value = "目标产品包")
	})
	@MethodLog(module = "商品包规则新增", insertDB = true, opterate = 1)
	public ResultBean add(@RequestBody PrdInfoRuleVo prdInfoRuleVo) {
		List<String> messageList = ValidateFilter.getFilterMessage(prdInfoRuleVo, Constants.VALIDATE_DEFAULT);
		if (!messageList.isEmpty()) {
			return ResultBean.error(messageList.toString());
		}
		if (prdInfoRuleVo.getIsprdSel() == 3) {
			if (prdInfoRuleVo.getTargetPrdInfo() == null) {
				return ResultBean.error("新增释放规则时，目标商品包不能为空");
			}
		}
		PrdInfoRule prdInfoRule = new PrdInfoRule();
		BeanUtils.copyProperties(prdInfoRuleVo, prdInfoRule);
		Set<PrdRuleSecondClassifyVo> secondClassifySet = prdInfoRuleVo.getSecondClassifys();
		HashSet<PrdRuleSecondClassify> set = new HashSet<>();

		if (secondClassifySet != null && secondClassifySet.size() > 0) {
			for (PrdRuleSecondClassifyVo secondClassifyVo : secondClassifySet) {
				List<String> messages = ValidateFilter.getFilterMessage(secondClassifyVo, Constants.VALIDATE_DEFAULT);
				if (!messages.isEmpty()) {
					return ResultBean.error(messages.toString());
				}
				PrdRuleSecondClassify classify = new PrdRuleSecondClassify();
				BeanUtils.copyProperties(secondClassifyVo, classify);
				set.add(classify);
			}
			prdInfoRule.setSecondClassifys(set);
		}
		if (isRepeat(prdInfoRuleVo))
			return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
		PrdInfoRule result = prdInfoRuleService.saveRuleAndSecondClassify(prdInfoRule);
		return ResultBean.ok(result);
	}

	private boolean isRepeat(PrdInfoRuleVo prdInfoRuleVo) {
		PrdInfoRule temp = new PrdInfoRule();
		CopyUtils.copyProperties(prdInfoRuleVo, temp, "prdRuleId");
		beanPropertiesUtil.setNullIfStringIsBlank(temp);
		List<PrdInfoRule> list = prdInfoRuleService.findAll(Example.of(temp));
		for (PrdInfoRule rule : list) {
			PrdInfoRuleVo vo = new PrdInfoRuleVo();
			PrdInfoRuleVo tempVo = new PrdInfoRuleVo();
			CopyUtils.copyProperties(rule, vo, "prdRuleId");
			CopyUtils.copyProperties(prdInfoRuleVo, tempVo, "prdRuleId");
			beanPropertiesUtil.setNullIfStringIsBlank(tempVo);
			beanPropertiesUtil.setNullIfStringIsBlank(vo);
			if (vo.equals(tempVo)) {
				if (prdInfoRuleVo.getPrdRuleId() == null || !Objects.equals(prdInfoRuleVo.getPrdRuleId(), rule.getPrdRuleId())) {
					return true;
				}
			}
		}
		return false;
	}

	@ApiOperation(value = "商品包规则 删除", notes = "商品包规则 删除")
	@ApiImplicitParam(name = "ids", required = true, dataType = "String", value = "规则id拼接字符串，以英文逗号分隔")
	@DeleteMapping(value = "/del")
	@MethodLog(module = "商品包规则删除", insertDB = true, opterate = 3)
	public ResultBean delete(String ids) {
		if (StringUtils.isNotBlank(ids)) {
			//规则id list  20210110 douzi 需要删除缓存
			List<Long> list = Arrays.stream(ids.split(",")).map(Long::valueOf).collect(Collectors.toList());
			for (Long id : list) {
				PrdInfoRule rule = prdInfoRuleService.findByPrdRuleId(id);
				prdInfoRuleService.delete(rule);
			}
			return ResultBean.ok();
		} else {
			return ResultBean.error("规则id不能为空");
		}
	}

	@ApiOperation(value = "商品包规则 更新", notes = "商品包规则 更新")
	@ApiImplicitParam(name = "id", required = true, dataType = "String", value = "商品包规则id")
	@PutMapping(value = "/update")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "prdRuleId", required = true, value = "规则id"),
			@ApiImplicitParam(name = "firstClassify", required = false, value = "一级分类"),
			@ApiImplicitParam(name = "assist", required = false, value = "辅助分类"),
			@ApiImplicitParam(name = "output", required = false, value = "是否可输出"),
			@ApiImplicitParam(name = "hasVideo", required = false, value = "是否包含媒体文件"),
			@ApiImplicitParam(name = "contentLevel", required = false, value = "内容评级"),
			@ApiImplicitParam(name = "formType", required = false, value = "剧集类型"),
			@ApiImplicitParam(name = "recommendation", required = false, value = "推荐标签"),
			@ApiImplicitParam(name = "category", required = false, value = "内容类别"),
			@ApiImplicitParam(name = "freeType", required = false, value = "资费类型"),
			@ApiImplicitParam(name = "mediaUsageCode", required = false, value = "码率"),
			@ApiImplicitParam(name = "optimal", required = false, value = "是否最优"),
			@ApiImplicitParam(name = "copyrightType", required = false, value = "版权类型"),
			@ApiImplicitParam(name = "copyRightCpId", required = false, value = "版权所属CP"),
			@ApiImplicitParam(name = "copytypeTal", required = false, value = "版权终端"),
			@ApiImplicitParam(name = "copyRightScope", required = false, value = "版权授权范围"),
			@ApiImplicitParam(name = "needDRM", required = false, value = "数字版权保护"),
			@ApiImplicitParam(name = "authorizationWay", required = false, value = "授权方式"),
			@ApiImplicitParam(name = "copyRightArea", required = false, value = "数字版权保护"),
			@ApiImplicitParam(name = "secondClassifyList", required = false, value = "二级分类"),
			@ApiImplicitParam(name = "targetPrdInfo", required = false, value = "目标产品包")
	})
	@MethodLog(module = "商品包规则更新", insertDB = true, opterate = 2)
	public ResultBean update(@RequestBody PrdInfoRuleVo vo) {
		List<String> messageList = ValidateFilter.getFilterMessage(vo, Constants.VALIDATE_UPDATE);
		if (!messageList.isEmpty()) {
			return ResultBean.error(messageList.toString());
		}
		if (vo.getIsprdSel() == 3) {
			if (vo.getTargetPrdInfo() == null) {
				return ResultBean.error("编辑释放规则时，目标商品包不能为空");
			}
		}
		if (isRepeat(vo))
			return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
		PrdInfoRule prdInfoRule = new PrdInfoRule();
		BeanUtils.copyProperties(vo, prdInfoRule);
		Set<PrdRuleSecondClassifyVo> secondClassifySet = vo.getSecondClassifys();
		HashSet<PrdRuleSecondClassify> set = new HashSet<>();
		PrdRuleSecondClassify classify = new PrdRuleSecondClassify();
		if (secondClassifySet != null && secondClassifySet.size() > 0) {
			for (PrdRuleSecondClassifyVo secondClassifyVo : secondClassifySet) {
				List<String> messages = ValidateFilter.getFilterMessage(secondClassifyVo, Constants.VALIDATE_UPDATE);
				if (!messages.isEmpty()) {
					return ResultBean.error(messages.toString());
				}
				BeanUtils.copyProperties(secondClassifyVo, classify);
				set.add(classify);
			}
			prdInfoRule.setSecondClassifys(set);
		}
		PrdInfoRule result = prdInfoRuleService.updateRuleAndSecondClassify(prdInfoRule);

		if (result != null) {
			return ResultBean.ok(result);
		} else {
			return ResultBean.error(MessageCodes.get(MessageCodes.M980000));
		}
	}

	@ApiOperation(value = "商品包规则 导入", notes = "商品包规则 导入")
	@PostMapping(value = "/import")
	@MethodLog(module = "商品包规则导入", insertDB = true, opterate = 6)
	public ResultBean ruleImport(MultipartFile file) {
		log.info("商品包规则导入:" + file.getOriginalFilename());
		try {
			EasyExcel.read(file.getInputStream(), PrdInfoRuleImportVo.class, new UploadDataListener(prdInfoRuleService, classifyService)).sheet("Sheet1").doRead();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ResultBean.ok("导入商品包规则成功");
	}


}
